import {observable, action, toJS} from 'mobx';
import {WeaTableNew, WeaForm} from 'comsMobx';
import {WeaLocaleProvider} from "ecCom";
import {message, Modal} from "antd";
import _ from 'lodash';
import * as contractManagementApi from '../api/ContractManagementApi';
import {indexOf, isBlank, parseIntValue} from '../util/CommonUtil';
import LanguageConstant from '../constant/LanguageConstant';
import * as Constant from '../constant/Constant';

const {getLabel} = WeaLocaleProvider;
const confirm = Modal.confirm
const {TableStore} = WeaTableNew;

class WorkflowSettingStore {

    /**
     * 权限控制
     */
    @observable authorized = true;

    /**
     * 加载状态标志
     *
     * @type {boolean}
     */
    @observable loading = false;

    /**
     * 选中的tab的key
     *
     * @type {string}
     */
    @observable selectedTabKey = Constant.WORKFLOW_SETTING_TAB_BASEINFO;

    /**
     * 基本信息设置表单
     *
     * @type {WeaForm}
     */
    @observable baseInfoSettingForm = new WeaForm();


    /**
     * 基本信息设置表单条件
     *
     * @type {Array}
     */
    @observable baseInfoSettingFormConditions = [];

    /**
     * 节点权限数据
     *
     * @type {Array}
     */
    @observable nodeOperateRightsDatas = [];

    /**
     * 节点权限表头
     *
     * @type {Array}
     */
    @observable nodeOperateRightsColumns = [];

    /**
     * 流程id
     *
     * @type {number}
     */
    @observable workflowId = -1;

    /**
     * 设置id
     */
    @observable settingId = -1;

    /**
     * 后台设置
     *
     * @type {{}}
     */
    @observable setting = {};

    /**
     * 流程模板关系数据
     *
     * @type {Array}
     */
    @observable workflowMouldRelationalDatas = [];

    /**
     * 流程模板关系列表中选中的数据
     *
     * @type {string}
     */
    @observable  workflowMouldRelationalSelectedRowKeys = [];

    /**
     * 书签匹配弹框是否显示
     *
     * @type {boolean}
     */
    @observable bookmarksMatchingDialogVisible = false;

    /**
     * 模板表格匹配弹框是否显示
     *
     * @type {boolean}
     */
    @observable mouldTableMatchingDialogVisible = false;

    /**
     * 弹框显示隐藏控制
     *
     * @type {boolean}
     */
    @observable dialogVisible = false;

    /**
     * 设置书签匹配的流程模板关系id
     *
     * @type {number}
     */
    @observable bookmarksMatchingWorkflowMouldRelationalId = -1;

    /**
     * 控制导入模板显示隐藏
     *
     * @type {boolean}
     */
    @observable importMouldsDialogVisible = false;

    /**
     * 控制设置合同名称规则弹框显示隐藏
     * @type {boolean}
     */
    @observable contractNameRuleDialogVisible = false;

    /**
     * 合同名称命名规则已修改
     *
     * @type {boolean}
     */
    @observable contractNameRuleEdited = false;

    /**
     * 导入模板选中的数据
     *
     * @type {string}
     */
    @observable importMouldSelectedRowKeys = "";

    /**
     * 导入模板弹框表格的store
     *
     * @type {TableStore}
     */
    @observable importMouldTableStore = new TableStore();

    /**
     * 接口动作设置数据
     *
     * @type {Array}
     */
    @observable actionSettings = [];

    /**
     * 接口动作设置数据下拉选择框选项
     *
     * @type {{}}
     */
    @observable actionSettingSelectOptions = {};

    /**
     * 接口动作删除的数据的id
     *
     * @type {Array}
     */
    actionSettingDeletedIds = [];

    /**
     * 接口动作设置浏览按钮属性
     *
     * @type {{}}
     */
    @observable actionSettingBrowserAttr = {};

    /**
     * 是否是多版本流程
     *
     * @type {boolean}
     */
    @observable isMultiVersion = false;

    /**
     * 多版本标题
     *
     * @type {string}
     */
    @observable multiVersionTitle = "";

    /**
     * 显示多版本
     *
     * @type {boolean}
     */
    @observable showMultiVersion = false;

    /**
     * 多版本数据
     *
     * @type {Array}
     */
    @observable multiVersionTab = [];

    /**
     * 更新加载状态
     *
     * @param bool
     */
    @action
    updateLoading = (bool) => {
        this.loading = bool;
    }

    /**
     * 设置属性
     * @param key
     * @param value
     * @returns {WorkflowSettingStore}
     */
    @action
    updateProperties = (params = {}) => {
        Object.keys(params).forEach(key => {
            this[key] = params[key];
        });
        return this;
    }

    /**
     * 设置多版本
     *
     */
    @action
    triggerMultiVersion = (callback) => {
        let v = this.showMultiVersion;
        this.showMultiVersion = !v;
        _.isFunction(callback) && callback();
        !v ? jQuery('.ant-tabs-extra-content a').css({color: '#00a9ff'})
            : jQuery('.ant-tabs-extra-content a').css({color: '#000'});
    }

    /**
     * 选择流程版本
     *
     * @param workflowId
     */
    chooseWorkflowVersion = (selectWorkflowId) => {
        let workflowId = parseIntValue("" + selectWorkflowId, -1);
        if (workflowId > 0) {
            this.resetWorkflowSetting();
            this.init({workflowId});
            this.getBaseInfoSettingForm();
        }
    }

    @action
    init = (params = {}) => {
        const {workflowId} = params;
        this.workflowId = workflowId;
        this.contractNameRuleEdited = false;
    }

    @action
    resetWorkflowSetting = () => {
        this.workflowId = -1;
        this.selectedTabKey = Constant.WORKFLOW_SETTING_TAB_BASEINFO;
        this.nodeOperateRightsDatas = [];
        this.nodeOperateRightsColumns = [];
        this.contractNameRuleEdited = false;
    }

    @action
    resetImportMouldsTable = () => {
        this.importMouldSelectedRowKeys = [];
    }

    /**
     * tab切换事件处理
     *
     * @param tabKey
     */
    @action
    onTabChange = (tabKey) => {
        this.selectedTabKey = tabKey;
    }

    /**
     * 检测自定义页面
     */
    detectCustomPage = () => {
        const workflowId = toJS(this.workflowId);
        const params = {workflowId};
        this.loading = true;
        contractManagementApi.detectCustomPage(params).then(res => {
            this.loading = false;
            const {code, data, notification} = res;
            if (code == 200) {
                const {occupied} = data ? data : {};
                if (notification) {
                    const script = '<script type="text/javascript" src="/contractmanagement/script/contractmanagement.js?v=20200518"></script>';
                    const style = '<link rel="stylesheet" type="text/css" href="/contractmanagement/style/contractmanagement.css?v=20200518"/>';
                    const config = {
                        width: occupied ? 900 : 600,
                        title: getLabel('518566', "信息确认"),
                        content: (
                            <div>
                                <p>{notification}</p>
                                {occupied ?
                                    <div>
                                        <p>{script}</p>
                                        <p>{style}</p>
                                    </div> : ""
                                }
                            </div>
                        ),
                    };
                    confirm(config);
                }
            } else {
                if (notification) {
                    message.error(notification);
                } else {
                    message.error(getLabel("518561", "操作失败"));
                }
            }

        });
    }


    /**
     * 获取基本信息表单
     *
     */
    @action
    getBaseInfoSettingForm = () => {
        const workflowId = toJS(this.workflowId);
        const params = {workflowId};
        contractManagementApi.getBaseInfoSettingForm(params).then(res => {
            const {code, data} = res;
            if (code == 200) {
                const {formConditions, nodeOperateRightTable, setting, versions} = data;
                const {datas: nodeOperateRightsDatas, columns: nodeOperateRightsColumns} = nodeOperateRightTable;
                const {id: settingId} = setting;
                this.baseInfoSettingFormConditions = formConditions;
                this.baseInfoSettingForm = new WeaForm();
                this.baseInfoSettingForm.initFormFields(formConditions);
                this.nodeOperateRightsColumns = nodeOperateRightsColumns;
                this.nodeOperateRightsDatas = nodeOperateRightsDatas;
                this.setting = setting;
                this.settingId = settingId;
                if (versions) {
                    const {multiVersionTab, isMultiVersion, title} = versions;
                    this.isMultiVersion = isMultiVersion;
                    this.multiVersionTab = multiVersionTab;
                    this.multiVersionTitle = title;
                }
            }
        });
    }

    /**
     * 节点权限表处理事件
     *
     * @param id
     * @param field
     * @param value
     */
    @action
    onNodeOperateRightsTableChange = (nodeId, field, value, record) => {
        const nodeOperateRightsDatas = toJS(this.nodeOperateRightsDatas);
        for (let i = 0; i < nodeOperateRightsDatas.length; i++) {
            let item = nodeOperateRightsDatas[i];
            if (item != undefined && item.nodeId == nodeId) {
                let checked = value == '1' ? true : false;
                item[field] = checked;
                break;
            }
        }
        this.nodeOperateRightsDatas = nodeOperateRightsDatas;
    }

    /**
     *保存基本信息
     */
    @action
    saveBaseInfoSetting = () => {
        if (!this.checkBaseInfoSettingFormMustInput()) {
            message.error(getLabel(LanguageConstant.PLEASE_FILL_MUSTINPUT_FIELD, "请填写必填内容"));
            return;
        } else {
            this.onSaveBaseInfoSetting();
        }
    }

    /**
     * 表单必填校验
     *
     * @returns {boolean}
     */
    @action
    checkBaseInfoSettingFormMustInput = () => {
        const formDatas = this.baseInfoSettingForm.getFormParams();
        const baseInfoSettingFormConditions = toJS(this.baseInfoSettingFormConditions);
        for (let j = 0; j < baseInfoSettingFormConditions.length; j++) {
            let formCondition = baseInfoSettingFormConditions[j];
            if (!formCondition && !formCondition.items) {
                continue;
            }
            const {items} = formCondition;
            for (let i = 0; i < items.length; i++) {
                let item = items[i];
                if (!item) {
                    continue;
                }
                const {viewAttr, domkey, otherParams} = item;
                if (viewAttr === 3 && _.isArray(domkey) && domkey.length > 0) {
                    const fieldname = domkey[0];
                    var value = formDatas[fieldname];
                    if (value != undefined && ("" + value).trim() != "") {
                        continue;
                    }
                    if (otherParams == undefined) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /**
     * 保存基本信息
     */
    @action
    onSaveBaseInfoSetting = () => {
        this.loading = true;
        const formDatas = this.baseInfoSettingForm.getFormParams();
        const workflowId = toJS(this.workflowId);
        const settingId = toJS(this.settingId);
        const nodeOperateRight = JSON.stringify(toJS(this.nodeOperateRightsDatas));
        const params = {
            ...formDatas, workflowId, nodeOperateRight, settingId
        }
        contractManagementApi.checkBaseInfoSetting(params).then(res => {
            const {code, notification} = res;
            if (code == 200) {
                contractManagementApi.saveBaseInfoSetting(params).then(res => {
                    const {code} = res;
                    this.loading = false;
                    if (code == 200) {
                        message.success(getLabel(LanguageConstant.SAVE_SUCCESS, "保存成功"));
                        this.getBaseInfoSettingForm();
                    } else {
                        message.error(getLabel(LanguageConstant.SAVE_FAIL, "保存失败"));
                    }
                });
            } else {
                this.loading = false;
                message.error(notification ? notification : getLabel(LanguageConstant.VERIFICATION_ERROR, "校验错误"));
            }
        });
    }

    /**
     * 获取流程模板关系列表
     *
     * @param params
     */
    @action
    getWorkflowMouldRelationalTable = (params = {}) => {
        const settingId = toJS(this.settingId);
        params = {...params, settingId};
        contractManagementApi.getWorkflowMouldRelationalDatas(params).then(res => {
            const {code, data} = res;
            if (code == 200) {
                this.workflowMouldRelationalDatas = data;
            }
        });
    }

    /**
     * 打开书签匹配弹框
     */
    @action
    openBookmarksMatchingDialog = (workflowMouldRelationalId) => {
        if (workflowMouldRelationalId > 0) {
            this.closeDialog();
            this.bookmarksMatchingWorkflowMouldRelationalId = workflowMouldRelationalId;
            this.dialogVisible = true;
            this.bookmarksMatchingDialogVisible = true;
        }
    }

    /**
     * 打开模板表格匹配弹框
     *
     * @param workflowMouldRelationalId
     */
    openMouldTableMatchingDialog = (workflowMouldRelationalId) => {
        if (workflowMouldRelationalId > 0) {
            this.closeDialog();
            this.bookmarksMatchingWorkflowMouldRelationalId = workflowMouldRelationalId;
            this.dialogVisible = true;
            this.mouldTableMatchingDialogVisible = true;
        }
    }

    /**
     * 打开设置合同名称规则弹框
     *
     * @param isDefault
     * @param mouldId
     */
    @action
    openContractNameRuleDialog = (isDefault, mouldId) => {
        this.closeDialog();
        this.dialogVisible = true;
        this.contractNameRuleDialogVisible = true;
    }

    /**
     * 关闭弹框
     */
    closeDialog = () => {
        this.dialogVisible = false;
        this.bookmarksMatchingWorkflowMouldRelationalId = -1;
        this.bookmarksMatchingDialogVisible = false;
        this.importMouldsDialogVisible = false;
        this.contractNameRuleDialogVisible = false;
        this.mouldTableMatchingDialogVisible = false;
        this.importMouldSelectedRowKeys = [];
    }

    /**
     * 删除流程模板关系
     */
    affirmWorkflowMouldRelationalDelete = (datas, keys) => {
        confirm({
            title: getLabel('518566', "信息确认"),
            content: getLabel('518567', "确定要删除吗？"),
            okText: getLabel('518568', "是"),
            cancelText: getLabel('518569', "否"),
            onOk: () => this.deleteWorkflowMouldRelational(keys),
            onCancel() {
            },
        });
    }

    /**
     * 删除流程模板关系
     *
     * @param keys
     */
    @action
    deleteWorkflowMouldRelational = (keys) => {
        const ids = keys.join(",");
        const params = {ids};
        contractManagementApi.deleteWorkflowMouldRelational(params).then(res => {
            const {code} = res;
            if (code == 200) {
                message.success(getLabel("518560", "操作成功"));
                this.getWorkflowMouldRelationalTable();
            } else {
                message.error(getLabel("518561", "操作失败"));
            }
        });
    }

    /**
     * 选择流程模板关系
     */
    onWorkflowMouldRelationalRowSelect = selectedRowKeys => {
        this.workflowMouldRelationalSelectedRowKeys = selectedRowKeys;
    }

    /**
     * 导入流程模板处理事件
     *
     * @param type
     * @param datas
     * @param keys
     */
    addWorkflowMouldRelationals = () => {
        this.openImportMouldsDialog();
    }

    /**
     * 打开导入模板按钮
     */
    @action
    openImportMouldsDialog = () => {
        this.closeDialog();
        this.importMouldsDialogVisible = true;
        this.dialogVisible = true;
    }

    /**
     * 导入模板弹框表格选中模板数据事件
     *
     * @param selectedKeys
     */
    @action
    importMouldRowSelection = (selectedKeys) => {
        this.importMouldSelectedRowKeys = selectedKeys;
    }

    /**
     * 加载导入模板表格数据
     */
    @action
    getImportMouldTableDatas = (params = {}) => {
        const settingId = toJS(this.settingId);
        const workflowId = toJS(this.workflowId);
        const fromImportDialog = true;
        params = {...params, settingId, workflowId, fromImportDialog};
        this.loading = true;
        contractManagementApi.getMouldList(params).then(res => {
            const {code, data} = res;
            this.loading = false;
            if (code == 200) {
                const {sessionkey} = data;
                this.importMouldTableStore.getDatas(sessionkey);
            }
        });
    }

    /**
     * 保存导入数据
     */
    @action
    onSaveImportMouldDatas = () => {
        const importMouldSelectedRowKeys = toJS(this.importMouldSelectedRowKeys);
        const settingId = toJS(this.settingId);
        const workflowId = toJS(this.workflowId);
        const params = {settingId, workflowId};
        if (importMouldSelectedRowKeys.length > 0) {
            this.loading = true;
            const mouldIds = importMouldSelectedRowKeys.join(",");
            contractManagementApi.saveWorkflowMouldRelational({...params, mouldIds}).then(res => {
                this.loading = false;
                const {code} = res;
                if (code == 200) {
                    message.success(getLabel("518560", "操作成功"));
                } else {
                    message.error(getLabel("518561", "操作失败"));
                }
                this.getWorkflowMouldRelationalTable();
                this.closeDialog();
            });
        } else {
            message.warn(getLabel("520346", "请选择数据"));
        }
    }

    /**
     * 获取节点设置数据
     */
    @action
    getWorkflowActionSettingDatas = () => {
        const settingId = toJS(this.settingId);
        const workflowId = toJS(this.workflowId);
        const params = {settingId, workflowId};
        contractManagementApi.getWorkflowActionSettingDatas(params).then(res => {
            const {code, data} = res;
            if (code == 200) {
                const {selectOptions, actionSettings, browserAttr} = data;
                this.actionSettings = actionSettings;
                this.actionSettingSelectOptions = selectOptions;
                this.actionSettingBrowserAttr = browserAttr;
            }
        });
    }

    @action
    initActionSetting = () => {
        this.actionSettingDeletedIds = [];
        this.actionSettings = [];
        this.actionSettingSelectOptions = {};
        this.actionSettingBrowserAttr = {};
        this.actionSettingDeletedIds = [];
    }

    /**
     * 节点设置字段值变化
     */
    @action
    onActionSettingChange = (data) => {
        this.actionSettings = data;
    }

    /**
     * 保存接口动作设置
     */
    saveActionSettingDatas = () => {
        if (this.actionSettings.length == 0 && toJS(this.actionSettingDeletedIds).length == 0) {
            message.error(getLabel(LanguageConstant.PLEASE_SELECT_ITEM, "请选择数据"));
            return;
        }
        if (!this.checkActionSettingDatasMustInput()) {
            message.error(getLabel(LanguageConstant.PLEASE_FILL_MUSTINPUT_FIELD, "请填写必填内容"));
            return;
        }
        const settingId = toJS(this.settingId);
        const actionSettingDeletedIds = toJS(this.actionSettingDeletedIds).join(",");
        const actionSettings = JSON.stringify(toJS(this.actionSettings));
        const params = {settingId, actionSettingDeletedIds, actionSettings};
        this.loading = true;
        contractManagementApi.saveWorkflowActionSetting(params).then(res => {
            const {code} = res;
            this.loading = false;
            if (code == 200) {
                if (code == 200) {
                    message.success(getLabel("518560", "操作成功"));
                    this.getWorkflowActionSettingDatas();
                } else {
                    message.error(getLabel("518561", "操作失败"));
                }
            }
        });
    }

    checkActionSettingDatasMustInput = () => {
        const actionSettings = toJS(this.actionSettings);
        for (let i = 0; i < actionSettings.length; i++) {
            let item = actionSettings[i];
            if (item.executePoint == undefined || item.executePoint == "" || item.executePoint <= 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * 新增行数据
     */
    @action
    onActionSettingRowAdd = (datas, addData) => {
        const defaultData = {executeType: 1, action: 1, rejectTrigger: 0, enable: 1};
        const actionSettings = toJS(this.actionSettings);
        let {id} = addData;
        id = "new_" + id;
        addData = {...addData, ...defaultData, id};
        actionSettings.push(addData);
        this.actionSettings = actionSettings;
        return actionSettings;
    }

    /**
     * 删除接口动作设置
     *
     * @param datas
     * @param keys
     */
    @action
    affirmDeleteActionSettingRow = (datas, keys) => {
        return new Promise((resolve, reject) => {
            confirm({
                title: getLabel('518566', "信息确认"),
                content: getLabel('518567', "确定要删除吗？"),
                okText: getLabel('518568', "是"),
                cancelText: getLabel('518569', "否"),
                onOk: () => {
                    this.onActionSettingRowDelete(datas, keys);
                    resolve(true)
                },
                onCancel: () => {
                    resolve(false);
                }
            });
        });
    }

    /**
     * 删除接口动作设置
     *
     * @param datas
     * @param keys
     */
    onActionSettingRowDelete = (datas, keys) => {
        const actionSettings = toJS(this.actionSettings);
        const actionSettingDeletedIds = toJS(this.actionSettingDeletedIds);
        for (let i = 0; i < keys.length; i++) {
            let key = keys[i];
            for (let j = 0; j < actionSettings.length; j++) {
                let {id} = actionSettings[j];
                if (id == key) {
                    actionSettings.splice(j, 1);
                    if (parseIntValue("" + id, -1) > 0) {
                        actionSettingDeletedIds.push(id);
                    }
                }
            }
        }
        this.actionSettingDeletedIds = actionSettingDeletedIds;
        this.actionSettings = actionSettings;
    }

    /**
     * 保存流程设置数据
     */
    @action
    saveWorkflowSetting = () => {
        const selectedTabKey = toJS(this.selectedTabKey);
        if (selectedTabKey == Constant.WORKFLOW_SETTING_TAB_BASEINFO) {
            this.saveBaseInfoSetting();
        } else if (selectedTabKey == Constant.WORKFLOW_SETTING_TAB_ACTIONSETTING) {
            this.saveActionSettingDatas();
        }
    }

}

export default WorkflowSettingStore;